<?php

class PhotosUploader extends Controller {

	function PhotosUploader()
	{
		parent::Controller();	
		$this->load->model('photomodel');
		$this->load->helper(array('form', 'url'));
	}
	
	function index(){
		$data['photos'] = $this->photomodel->getPhotosFromNote('1');
		$data['photos_directory'] = '../files/photos/squares100/'; 
		$data['error'] = '';
		//$this->load->view('photoform', $data);
		$this->load->view('swfphotoform');
	}
	function photoAlbum(){
		/*return a json object containing the photos filename of the posted note */
		if(count($_POST)>0){
			$id_note = $_POST['idNote'];
			///print_r($id_note); 
			$photos = $this->photomodel->getPhotosFromNote(''.$id_note.'');//$id_note);
			//print_r($photos);
			echo "{photos_directory : '".base_url().'files/photos/'."',\n photoAlbum :[\n";
			for($i=0; $i<sizeof($photos); $i++){
				echo "{ id : '".$photos[$i]->id."', ";
				echo "filename : '".$photos[$i]->filename."'},\n";
			}
			echo "]}";
		}
	}
	function orderPhoto(){
		if(count($_POST)>0){
			print_r($_POST);
		}
	}
	function uploadPhotoSWF() {
		/* Upload using swf library */
	        $config['upload_path'] = './files/photos/temp/';
	        $config['allowed_types'] = 'jpg|JPG';
	        $config['max_size']    = '1000';
	        $config['max_width']  = '1024';
	        $config['max_height']  = '768';
					
					$id_note = $_POST['idnotejm'];
					
	        $this->load->library('upload', $config);
			//$this->upload->do_upload('Filedata');
			if ( ! $this->upload->do_upload('Filedata'))
			{
				$error = array('error' => $this->upload->display_errors());

				$this->load->view('upload_form', $error);
			}    
			else
			{
				$res = $this->upload->data();
				$this->savePhoto($res['file_name'], $id_note);
				echo $res['file_name'];
			}

	 }

			
	function uploadPhoto()
	{
		/* This part is the classic Code Igniter upload */
		$config['upload_path'] = './files/photos/temp/' ;
		$config['allowed_types'] = 'jpg|JPG';
		$config['max_size']	= '100';
		$config['max_width']  = '1024';
		$config['max_height']  = '768';
		
		$this->load->library('upload', $config);

		if ( ! $this->upload->do_upload())
		{
			$error = array('error' => $this->upload->display_errors());

			$this->load->view('photoform', $error);
		}	
		else
		{
		$data = array('uploaded_photo' => $this->upload->data());
		$filename = $data['uploaded_photo']['file_name'];
		$this->savePhoto($filename);
		
		}
	}
	function geotagPhoto(){
		
	}
	function savePhoto($filename, $id){
		/* Make crop versions of the uploaded photo */
		/* First a simple copy from temporary folder*/ 
		$this->load->library('image_lib');

		//var_dump(gd_info()); 
		$config['image_library'] = 'gd2';
		$config['source_image'] = './files/photos/temp/'.$filename;//$data['uploaded_photo']['full_path'];
		//$config['create_thumb'] = TRUE;
		$config['new_image'] = './files/photos/big/'.$filename;//$data['uploaded_photo']['file_name'];
		//$config['dest_image'] = './files/photos/squares100/';
		$config['maintain_ratio'] = TRUE;


		$this->image_lib->initialize($config); 
		$this->load->library('image_lib', $config);
		$this->image_lib->resize();
		
		/* Small version */
		$config['new_image'] = './files/photos/small/'.$filename;//$data['uploaded_photo']['file_name'];
		//$config['dest_image'] = './files/photos/small/';
		$config['height'] = 300;

		$this->image_lib->initialize($config); 
		$this->load->library('image_lib', $config);
		$this->image_lib->resize();
		if ( ! $this->image_lib->resize())
		{
			echo $this->image_lib->display_errors();
		}
		
		/* Resize 100*100 version */
		$config['new_image'] = './files/photos/squares100/'.$filename;//$data['uploaded_photo']['file_name'];
		//$config['dest_image'] = './files/photos/squares100/';
		$config['maintain_ratio'] = FALSE; // @todo(for Leopold), croping image after resizing.
		$config['width'] = 100;
		$config['height'] = 100;

		$this->image_lib->initialize($config); 
		$this->load->library('image_lib', $config);
		if ( ! $this->image_lib->resize())
		{
			echo $this->image_lib->display_errors();
		}
		
		/* Resize 50*50 version */
		$config['new_image'] = './files/photos/squares50/'.$filename;//$data['uploaded_photo']['file_name'];
		//$config['dest_image'] = './files/photos/squares50/';
		$config['width'] = 50;
		$config['height'] = 50;

		$this->image_lib->initialize($config); 
		$this->load->library('image_lib', $config);
		if ( ! $this->image_lib->resize())
		{
			echo $this->image_lib->display_errors();
		}

		

		/*$this->cropImage(100, 100, $data['uploaded_photo']['full_path'], $data['uploaded_photo']['image_type'], '/Applications/MAMP/htdocs/blognmap/files/photos/squares100/'.$data['uploaded_photo']['file_name']);
		*/

		/* Save the photo in db */
		$data['id_photo'] = $this->photomodel->insertPhoto($filename, $id);
		/* Delete temporary phtoto*/
		@unlink('./files/photos/temp/'.$filename);
		//$this->load->view('upload_success', $data);
	}
	function deletePhoto(){
		if(count($_POST) > 0){
			$id = $_POST['imageId'];
			$photo = $this->photomodel->getPhoto($id);
			print_r($photo);	
			unlink('./files/photos/big/'.$photo->filename);
			unlink('./files/photos/squares100/'.$photo->filename);
			unlink('./files/photos/squares50/'.$photo->filename);
			unlink('./files/photos/small/'.$photo->filename);
			$this->photomodel->deletePhoto($id);
	}
	}	
	function submitAlbum(){
		
		
	}
	function cropImage($nw, $nh, $source, $stype, $dest){
		$size = getimagesize($source);
		$w = $size[0];
		$h = $size[1];
		switch($stype){
			case 'gif':
			$simg = imagecreatefromgif($source);
			break;
			case 'jpeg':
			$simg = imagecreatefromjpeg($source);
			break;
			case 'png':
			$simg = imagecreatefrompng($source);
			break;
		}
		$dimg = imagecreatetruecolor($nw, $nh);
		$wm = $w/$nw;
		$hm = $h/$nh;
		$h_height = $nh/2;
		$w_height = $nw/2;
		if($w> $h) {
			$adjusted_width = $w / $hm;
			$half_width = $adjusted_width / 2;
			$int_width = $half_width - $w_height;
			imagecopyresampled($dimg,$simg,-$int_width,0,0,0,$adjusted_width,$nh,$w,$h);
		} elseif(($w <$h) || ($w == $h)) {
			$adjusted_height = $h / $wm;
			$half_height = $adjusted_height / 2;
			$int_height = $half_height - $h_height;
			imagecopyresampled($dimg,$simg,0,-$int_height,0,0,$nw,$adjusted_height,$w,$h);
		} else {
			imagecopyresampled($dimg,$simg,0,0,0,0,$nw,$nh,$w,$h);
		}
		imagejpeg($dimg,$dest,100);
	}
	/*function uploadPhotoPHP(){
		//$data['photos'] = $this->photomodel->savePhotos();
		//print_r($data['photos']);
		print_r($_FILES);
		$targetdir = base_url() . "files/photos/big/" ;
		foreach($_FILES as $file)
		{
		    if($file['error'] == 0 && $file['size'] > 0)
		    {
		        move_uploaded_file($file['tmp_name'], $targetdir.$file['name']);
		    }
		}
		/*if ((($_FILES["file"]["type"] == "image/gif")
			|| ($_FILES["file"]["type"] == "image/jpeg"))
			&& ($_FILES["file"]["size"] < 20000))
		{
			if ($_FILES["file"]["error"] > 0)
			{
				echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
			}
			else
			{
				if (file_exists(base_url(). "/files/photos/big/" . $_FILES["file"]["name"]))
				{
					echo $_FILES["file"]["name"] . " already exists. ";
				}
				
			}
		}
		else{
			echo "Photo size is too big or not in the right format (gif or jpeg)";
		}
		//$this->output->set_header('Content-type:text/xml; charset=utf-8');
	}*/
	
	function editPhotos(){
		$this->load->model('photomodel');
		$this->notemodel->editPhotos();
	}
	
	function SWFthumbnails(){
		/* Note: This thumbnail creation script requires the GD PHP Extension.  
			If GD is not installed correctly PHP does not render this page correctly
			and SWFUpload will get "stuck" never calling uploadSuccess or uploadError
		 */

		// Get the session Id passed from SWFUpload. We have to do this to work-around the Flash Player Cookie Bug
		if (isset($_POST["PHPSESSID"])) {
			session_id($_POST["PHPSESSID"]);
		}

		session_start();

		// Check the upload
		if (!isset($_FILES["Filedata"]) || !is_uploaded_file($_FILES["Filedata"]["tmp_name"]) || $_FILES["Filedata"]["error"] != 0) {
			header("HTTP/1.1 500 Internal Server Error");
			echo "invalid upload";
			exit(0);
		}

		// Get the image and create a thumbnail
		$img = @imagecreatefromjpeg($_FILES["Filedata"]["tmp_name"]);
		if (!$img) {
			header("HTTP/1.1 500 Internal Server Error");
			echo "could not create image handle";
			exit(0);
		}

		$width = imageSX($img);
		$height = imageSY($img);

		if (!$width || !$height) {
			header("HTTP/1.1 500 Internal Server Error");
			echo "Invalid width or height";
			exit(0);
		}

		// Build the thumbnail
		$target_width = 100;
		$target_height = 100;
		$target_ratio = $target_width / $target_height;

		$img_ratio = $width / $height;

		if ($target_ratio > $img_ratio) {
			$new_height = $target_height;
			$new_width = $img_ratio * $target_height;
		} else {
			$new_height = $target_width / $img_ratio;
			$new_width = $target_width;
		}

		if ($new_height > $target_height) {
			$new_height = $target_height;
		}
		if ($new_width > $target_width) {
			$new_height = $target_width;
		}

		$new_img = ImageCreateTrueColor(100, 100);
		if (!@imagefilledrectangle($new_img, 0, 0, $target_width-1, $target_height-1, 0)) {	// Fill the image black
			header("HTTP/1.1 500 Internal Server Error");
			echo "Could not fill new image";
			exit(0);
		}

		if (!@imagecopyresampled($new_img, $img, ($target_width-$new_width)/2, ($target_height-$new_height)/2, 0, 0, $new_width, $new_height, $width, $height)) {
			header("HTTP/1.0 500 Internal Server Error");
			echo "Could not resize image";
			exit(0);
		}

		if (!isset($_SESSION["file_info"])) {
			$_SESSION["file_info"] = array();
		}

		// Use a output buffering to load the image into a variable
		ob_start();
		imagejpeg($new_img);
		$imagevariable = ob_get_contents();
		ob_end_clean();

		$file_id = md5($_FILES["Filedata"]["tmp_name"] + rand()*100000);

		$_SESSION["file_info"][$file_id] = $imagevariable;

		echo $file_id;	// Return the file id to the script
	}
	
}

/* End of file photosuploader.php */
/* Location: ./system/application/controllers/photosuploader.php */
?>